<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="filters">
                <el-form-item label="会议室">
                    <el-select 
                    v-model="form.room" 
                    placeholder="请选择会议室">
                         <div v-for="item in rooms" :key="item.id" >
                            <el-option :label="item.roomName" :value="item.id">{{item.roomName}}</el-option>
                        </div>
                    </el-select>
                </el-form-item>
                <el-form-item label="会议时间">
                    <el-date-picker
                            v-model="filters.column.create_start_date"
                            type="date"
                            :picker-options="pickerBeginDateBefore"
                            format="yyyy-MM-dd"
                            placeholder=""
                    >
                    </el-date-picker>
                </el-form-item>
                <el-form-item label="至" label-width="25px">
                    <el-date-picker
                            v-model="filters.column.create_end_date"
                            type="date"
                            format="yyyy-MM-dd"
                            :picker-options="pickerBeginDateAfter"
                            placeholder="">
                    </el-date-picker>
                     <!-- <el-form-item prop="date">
                    <el-date-picker type="date" placeholder="选择日期" v-model="defaultDayDate" style="width: 100%;"></el-date-picker>
                </el-form-item> -->
                </el-form-item >
                <el-form-item label="会议主题" style="width:60%;">
                    <el-input v-model="theme"></el-input>
                </el-form-item>

                <el-form-item style="margin-left: 70px;">
                    <el-button type="primary" v-on:click="getAppointmentDetails" >查询</el-button>
                </el-form-item>
            </el-form>
        </el-col>

        <!--列表-->
        <el-table :data="appointmentDetails" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
            <el-table-column type="selection" width="55">
            </el-table-column>
            <!-- <el-table-column type="index" width="60">
            </el-table-column> -->
            <el-table-column prop="roomName" label="会议室名称"   width="160" sortable>
            </el-table-column>
            <el-table-column prop="theme" label="会议主题"   width="160" sortable>
            </el-table-column>
            <el-table-column prop="startAt" label="开始时间"  min-width="120" sortable>
			</el-table-column>
			<el-table-column prop="endAt" label="结束时间" min-width="120" sortable>
			</el-table-column>
            <el-table-column label="操作" width="160">
                <template scope="scope">
                    <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--工具条-->
        <el-col :span="24" class="toolbar">
            <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
            <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange" :page-size="20" :total="total" style="float:right;">
            </el-pagination>
        </el-col>

        <!--编辑界面-->
        <el-dialog title="编辑" v-model="editFormVisible" :close-on-click-modal="false">
            <el-form :model="editForm" :rules="editFormRules" ref="editForm" label-width="100px" class="demo-ruleForm">
                <!-- <el-form-item label="预约人" prop="name">
                    <el-input v-model="editForm.name" style="width:23%;"></el-input>
                </el-form-item> -->
                 <el-form-item label="预约人" prop="name">
            <span>{{ editForm.applyUserName }}&nbsp;/&nbsp;{{ editForm.applyDeptName }}</span>
        </el-form-item>

                <!-- <el-form-item label="预约部门" prop="department">
                    <el-select v-model="editForm.department" clearable placeholder="请选择部门">
                        <el-option label="研发部" value="department1"></el-option>
                        <el-option label="市场部" value="department2"></el-option>
                    </el-select>
                </el-form-item> -->
                <!-- <el-form-item label="会议室" prop="room">
                    <el-select v-model="editForm.room" clearable placeholder="请选择会议室">
                        <el-option label="庐山" value="room1"></el-option>
                        <el-option label="嵩山" value="room2"></el-option>
                    </el-select>
                </el-form-item> -->
                <!-- <el-form-item label="会议室">
			<el-select 
                v-model="editForm.selectedApply" 
                placeholder="请选择会议室" 
                @change="getApplyEquips"
            >
            <div v-for="item in editForm.applyRooms" :key="item.id">
                <el-option :label="item.roomName" :value="item.id">{{item.roomName}}</el-option>
            </div>
		    </el-select>
		</el-form-item> -->
        <el-form-item label="会议室">
                    <el-select 
                    v-model="form.room" 
                    placeholder="请选择会议室">
                         <div v-for="item in rooms" :key="item.id" >
                            <el-option :label="item.roomName" :value="item.id">{{item.roomName}}</el-option>
                        </div>
                    </el-select>
                </el-form-item>
                <el-form-item label="会议主题" prop="theme">
                    <el-input v-model="editForm.theme" style="width:46%;"></el-input>
                </el-form-item>
                <el-form-item label="会议时间" required>
                    <el-col :span="9">
                        <el-form-item prop="date">
                            <el-date-picker type="date" placeholder="选择日期" v-model="editForm.date" style="width: 100%;"></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :span="5" style="margin-left:45px;">
                        <el-form-item prop="time" >
                            <el-time-picker is-range v-model="editForm.time " range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间" placeholder="选择时间范围" value-format="HH:mm" format="HH:mm">
                            </el-time-picker>
                        </el-form-item>
                    </el-col>
                </el-form-item>
                <el-form-item label="设备需求" prop="typ">
                    <el-checkbox-group v-model="editForm.type">
                        <el-checkbox label="激光笔" name="type"></el-checkbox>
                        <el-checkbox label="八爪鱼" name="type"></el-checkbox>
                        <el-checkbox label="投影仪" name="type"></el-checkbox>
                        <el-checkbox label="电视" name="type"></el-checkbox>
                    </el-checkbox-group>
                </el-form-item>
                <el-form-item label="备注" prop="remark">
                    <el-input type="textarea" v-model="editForm.remark" style="width:46%;"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
                <el-button @click.native="editFormVisible = false">取消</el-button>    
            </div>
        </el-dialog>
    </section>
</template>

<script>
    import util from '../../common/js/util'
    //import NProgress from 'nprogress'
    import { getRoomList, getAppointmentDetailsList,getApplyEquipsList, removeUser, batchRemoveUser, editUser, addUser,getDepartmentList } from '../../api/api';

    export default {
        data() {
            return {
                filters: {
                    name: ''
                },
                selected: '',
                appointmentDetails:[],
                rooms:[],
                total: 0,
                page: 1,
                listLoading: false,
                sels: [],//列表选中列
                defaultDayDate: new Date(),
                editFormVisible: false,//编辑界面是否显示
                editLoading: false,
                editFormRules: {
                     name: [
                        { required: false, message: '请输入预约人', trigger: 'blur' },
                       
                    ],
                    department: [
                        { required: true, message: '请选择部门', trigger: 'change' }
                    ],
                    room: [
                        { required: true, message: '请选择会议室', trigger: 'change' }
                    ],
                    theme: [
                        { required: true, message: '请输入会议主题', trigger: 'change' }
                    ],
                    date: [
                        { type: 'date', required: true, message: '请选择日期', trigger: 'change' }
                    ],
                    time: [
                        { type: 'date', required: true, message: '请选择时间范围', trigger: 'change' }
                    ],
                },
                //编辑界面数据
                editForm: {
                   name: '',
                    department: '',
                    date: '',
                    time: '',
                    room:'',
                    theme:'',
                    remark:'',
                    type: [],
                    applyUserName: '',
                    applyDeptName: '',
                    roomName:'',
                    selectedApply: '',
                    applyRooms: [],
                },     
                pickerOptions0: {
                    disabledDate: (time) => {
                        if (this.value2 != "") {
                            return time.getTime() > Date.now() || time.getTime() > this.value2;
                        } else {
                            return time.getTime() > Date.now();
                        }

                    }
                },
                pickerOptions1: {
                    disabledDate: (time) => {
                        return time.getTime() < this.value1 || time.getTime() > Date.now();
                    }
                },
                filters: {
                    column: {
                        create_start_date: '',
                        create_end_date: ''
                    },
                },
                pickerBeginDateBefore:{
                    disabledDate: (time) => {
                        let beginDateVal = this.filters.column.create_end_date;
                        if (beginDateVal) {
                            return time.getTime() > beginDateVal;
                        }
                    }
                },
                pickerBeginDateAfter:{
                    disabledDate: (time) => {
                        let beginDateVal = this.filters.column.create_start_date;
                        if (beginDateVal) {
                            return time.getTime() < beginDateVal;
                        }
                    }
                },
                form: {
                    name: '',
                    delivery: false,
                    resource: '',
                    remark: '',
                    desc: '',
                    department:'',
                    room:'',
                    theme:'',
                    time: [new Date(2016, 9, 10, 8, ), new Date(2016, 9, 10, 9, )],

                },
            }

        },

        methods:{
            //性别显示转换
            // formatSex: function (row, column) {
            //     return row.sex == 1 ? '男' : row.sex == 0 ? '女' : '未知';
            // },
            handleCurrentChange(val) {
                this.page = val;
                this.getUsers();
            },
            //获取预约列表
            getRooms() {
                getRoomList().then((data) => {
                    var roomArr = eval(data);
                    
                    for(var i=0;i<roomArr.length;i++){

                        if( i == 0 ){
                            this.selected = roomArr[i].id;
                        }
                        if(roomArr[i].status == 0){
                            roomArr[i].status = '空闲';
                        }
                        
                        if(roomArr[i].status == 1){
                            roomArr[i].status = '被占用';
                        }
                    }
                    this.rooms = roomArr;
                    this.listLoading = false;
                    this. getAppointmentDetails();
                });
            },
            //获取预约详情
             getAppointmentDetails() {
                var id = '';
                // let roomId = this.selected;
                // let date = dateFtt("yyyy-MM-dd",this.defaultDayDate);
                // let para = { roomId, date };
                var user = sessionStorage.getItem('user');
                if (user) {
                    user = JSON.parse(user);
                    id = user.id;
                }
                 getAppointmentDetailsList(id).then((params) => {
                   var arr = eval(params).bookDetailDTOList;
                    for(var i = 0;i < arr.length;i++){
                        arr[i].startAt = format(parseInt(arr[i].startAt));
                        arr[i].endAt = format(parseInt(arr[i].endAt));                       
                    }
                    this.appointmentDetails = arr;
                    this.listLoading = false;
                });
            },
             //获取当前登陆人员所在的部门
            getDepartment() {
                var user = sessionStorage.getItem('user');
                var userId = '';
                if (user) {
                     user = JSON.parse(user);
                     this.editForm.applyUserName = user.username || '';
                     userId = user.id;
                }
                let para = { userId }
                this.editForm.applyDeptName = 'a';
                getDepartmentList(userId).then((params) => {
                    this.editForm.applyDeptName = params.data.departmentName;
                });
            },
            //将会议室名称显示在“预约申请界面”
            getApplyRooms() {
                //NProgress.start();
                getApplyRoomList().then((data) => {
                    var roomArr = eval(data);
                    for(var i=0;i<roomArr.length;i++){
                        if( i == 0 ){
                            this.ruleForm.selectedApply = roomArr[i].id;
                        }   
                    }
                    this.ruleForm.applyRooms = roomArr;
                    this.listLoading = false;
                });
                this.getApplyEquips();
            },
            //将用户选择的会议室中的设备显示在“预约申请界面”
            getApplyEquips() {
                var roomId = this.ruleForm.selectedApply;
                // this.ruleForm.equips = ["八爪鱼",'投影仪'];
                getApplyEquipsList(roomId).then((params) => {
                    var equipsArr = [];
                    for(var i=0;i<params.length;i++){
                        equipsArr.push(params[i].name);
                    }
                    this.ruleForm.equips = equipsArr;
                    this.listLoading = false;
                });
            },
            //显示编辑界面
            handleEdit: function (index, row) {
                this.editFormVisible = true;
            },
            //编辑
            editSubmit: function () {
                this.$refs.editForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.editLoading = true;
                            let para = Object.assign({}, this.editForm);
                            para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
                            editUser(para).then((res) => {
                                this.editLoading = false;
                                this.$message({
                                    message: '提交成功',
                                    type: 'success'
                                });
                                this.$refs['editForm'].resetFields();
                                this.editFormVisible = false;
                                this.getUsers();
                            });
                        });
                    }
                });
            },
            selsChange: function (sels) {
                this.sels = sels;
            },
             handleDel: function (index, row) {
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    let para = { id: row.id };
                    removeUser(para).then((res) => {
                        this.listLoading = false;
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        this.getAppointmentDetails();
                    });
                }).catch(() => {

                });
            },
            //批量删除
            batchRemove: function () {
                var ids = this.sels.map(item => item.id).toString();
                this.$confirm('确认删除选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    let para = { ids: ids };
                    batchRemoveUser(para).then((res) => {
                        this.listLoading = false;
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        this.getAppointmentDetails();
                    });
                }).catch(() => {

                });
            }
        },
        mounted() {
            this.getRooms();
            this.getAppointmentDetails();
            this.getDepartment();
            this.getApplyRooms();
        },
      submitForm(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    alert('submit!');
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
        }
    }
//将日期格式化为 2018-07-24
function dateFtt(fmt,date)   
{ //author: meizz   
  var o = {   
    "M+" : date.getMonth()+1,                 //月份   
    "d+" : date.getDate(),                    //日   
    "h+" : date.getHours(),                   //小时   
    "m+" : date.getMinutes(),                 //分   
    "s+" : date.getSeconds(),                 //秒   
    "q+" : Math.floor((date.getMonth()+3)/3), //季度   
    "S"  : date.getMilliseconds()             //毫秒   
  };   
  if(/(y+)/.test(fmt))   
    fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));   
  for(var k in o)   
    if(new RegExp("("+ k +")").test(fmt))   
  fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));   
  return fmt;   
} 

//将时间戳转换成 2018-07-24 08:00:00 格式
function add0(m){return m<10?'0'+m:m }
function format(shijianchuo)
{
//shijianchuo是整数，否则要parseInt转换
var time = new Date(shijianchuo);
var y = time.getFullYear();
var m = time.getMonth()+1;
var d = time.getDate();
var h = time.getHours();
var mm = time.getMinutes();
var s = time.getSeconds();
return y+'-'+add0(m)+'-'+add0(d)+' '+add0(h)+':'+add0(mm)+':'+add0(s);
}

</script>

<style scoped>

</style>